package top.cyuw.subjectsystem.exception;

import top.cyuw.subjectsystem.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.ui.Model;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @InitBinder
    public void initWebBinder(WebDataBinder binder) {

    }

    @ModelAttribute
    public void addAttribute(Model model) {

    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseVo<String> accessDeniedExceptionHandler(AccessDeniedException e) {
        return ResponseVo.newResponse(403, "无权操作", null);
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public ResponseVo<String> exceptionHandler(Exception e) {
        if (!(e instanceof HttpMediaTypeNotSupportedException)) {
            log.error(e.getMessage(), e);
        }
        if (e instanceof ServiceException) {
            ServiceException err = (ServiceException) e;
            return ResponseVo.newResponse(err.getCode(), err.getMsg(), null);
        }
        return ResponseVo.newResponse(500, "系统内部错误", null);
    }
}